<template>
  <div class="trainList-wrapper">
    <v-header :title="trainQuery.startStationName + ' → ' + trainQuery.endStationName"></v-header>
    <div class="calendar-opt">
      <p class="pre" :class="{disabled: departureDate === moment().format('YYYY-MM-DD')}" @click="pre">前一天</p>
      <p class="date" @click="showCalendar = true"><i class="fa fa-calendar-minus-o" aria-hidden="true"></i>  {{departureDateStr}}  <i class="fa fa-caret-down" aria-hidden="true"></i></p>
      <p class="next" @click="next">后一天</p>
    </div>
    <transition name="fade">
      <p class="query-tip" v-if="showQueryTip" :style="{top: 89 + paddingTop + 'px'}">{{queryTip}}</p>
    </transition>
    <scroll ref="scroll"
      :data="trainList"
      :probeType="3"
      :listenScroll="true"
      @scroll="scroll"
      @scrollStart="scrollStart"
      :pullDownRefresh="true" @pullingDown="_queryTrain"
      :style="{height: scrollHeight + 'px'}" >
      <ul class="train-list">
        <li class="train-item" v-for="train in trainList" :key="train.lch">
          <div class="main">
            <div class="left">
              <div class="left-item">
                <p class="time" :class="{'active-text': isSortTime}">{{train.cfsj}}</p>
                <p class="name">{{train.cfzw}}</p>
              </div>
              <div class="left-item center">
                <p :class="{'active-text': isSortDuration}">{{train.totalTime}}</p>
                <div class="line" :class="{active1: train.cfzw === train.sfzd, active2: train.ddzw === train.zdzd}"></div>
                <p>{{train.cch}}</p>
              </div>
              <div class="left-item">
                <p class="time">{{train.ddsj}}</p>
                <p class="name">{{train.ddzw}}</p>
              </div>
            </div>
            <div class="right">
              <p class="price">￥{{train.price}}</p>
              <p v-if="train.tsyy == '预订'" class="btn" @click.stop="order">{{train.tsyy}}</p>
              <p v-else class="toast">{{train.tsyy}}</p>
            </div>
          </div>
          <ul class="bottom" v-if="train.zwjh && train.zwjh.length > 0">
            <li v-for="(item, index) in train.zwjh" :key="index" :class="{'no-ticket': item.ypsl == 0 || item.ypsl == '无'}">
              {{item.zwmc + ': '}}
              <span v-if="!isShowPrice" :style="{color: item.ypsl === '有' ? '#00ceb9' : ''}">{{item.ypsl == '有' || item.ypsl == '无' ? item.ypsl : (item.ypsl + '张')}}</span>
              <span v-else :style="{color: item.ypsl === '有' ? '#00ceb9' : ''}">￥{{item.cpjg}}</span>
            </li>
          </ul>
        </li>
      </ul>
    </scroll>
    <ul class="bottom-opt" ref="bottomOpt">
      <li :class="{'active-text': isSortTime}" @click.stop="sortByTime">出发时间</li>
      <li :class="{'active-text': isSortDuration}" @click.stop="sortByDuration">旅行耗时</li>
      <li  @click.stop="isShowPrice = !isShowPrice">显示{{isShowPrice ? '余票' : '价格'}}</li>
    </ul>

    <transition name="fade">
      <div class="calender-wrapper" @click="showCalendar = false" v-show="showCalendar">
        <div class="calendar-dropdown" @click.stop="() => {}">
          <calendar :zero="calendarOpt.zero" :lunar="calendarOpt.lunar" :value="calendarOpt.value" :begin="calendarOpt.begin" :end="calendarOpt.end" @select="calendarOpt.select"></calendar>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import Scroll from '@/components/scroll/scroll'
import Calendar from '@/components/calendar/calendar'

import { isIphoneX } from '@/assets/js/brower'
import axios from '@/api/axiosApi'
import { mapGetters } from 'vuex'

export default {
  data () {
    return {
      showQueryTip: false,
      showCalendar: false,
      isSortTime: true,
      isSortDuration: false,
      isShowPrice: false,
      queryTip: '',
      departureDate: this.moment().format('YYYY-MM-DD'),
      trainList: [],
      calendarOpt: {
        zero: true,
        value: this.moment().toArray().slice(0, 3), // 默认日期
        lunar: true, // 显示农历
        begin: this.moment().toArray().slice(0, 3),
        end: this.moment().add(3, 'months').toArray().slice(0, 3),
        select: (value) => {
          if (this.showCalendar === false) return
          this.showCalendar = false
          this.calendarOpt.value = value
          this.departureDate = this.moment(value).format('YYYY-MM-DD')
        }
      }
    }
  },
  components: {
    VHeader, Scroll, Calendar
  },
  computed: {
    departureDateStr () {
      const diffDays = this.moment(this.departureDate).diff(this.moment().format('YYYY-MM-DD'), 'days')
      if (diffDays === 0) {
        return this.moment(this.departureDate).format('M月D日') + ' 今天'
      }
      if (diffDays === 1) {
        return this.moment(this.departureDate).format('M月D日') + ' 明天'
      }
      return this.moment(this.departureDate).format('M月D日 dddd')
    },
    ...mapGetters(['trainQuery'])
  },
  created () {
    this.paddingTop = 24
    if (isIphoneX()) {
      this.paddingTop = 34
    }
    this.scrollHeight = window.innerHeight - 50 - 40 - this.paddingTop
    this.departureDate = this.trainQuery.departureDate
    this._queryTrain()
  },
  destroyed () {
    this.$store.commit('SET_TRAIN_QUERY', null)
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
  methods: {
    _queryTrain () {
      if (this.trainQuery == null) {
        this.$vux.toast.text('请输入出发日期', 'middle')
        return
      }
      const params = this.trainQuery
      axios.post(this, '/v1/train', {
        method: 'TRAIN_B2C_getTrainList',
        start: 1,
        count: 5,
        ccrq: this.moment(this.departureDate).format('YYYY-MM-DD'),
        cfzd: params.startStationCode,
        ddzd: params.endStationCode
      }, (data) => {
        if (data == null || data.res == null) {
          this.$vux.toast.text('查询结果异常，数据不存在', 'middle')
          return
        }
        if (data.res.sts !== 1) {
          console.error(data.res.emg)
        }
        if (data.res.erc !== 0 && data.res.erc !== 'SUCCESS') {
          this.$vux.toast.text(data.res.rtp)
          return
        }
        //
        const list = data.res.ccjh
        list.forEach(train => {
          const hour = parseInt(train.yxsj / 60)
          const minus = train.yxsj % 60
          if (hour === 0) {
            train.totalTime = minus + '分钟'
          } else {
            train.totalTime = hour + '小时' + minus + '分'
          }
          if (train.zwjh && train.zwjh.length > 0) {
            train.price = train.zwjh[train.zwjh.length - 1].cpjg
            train.zwjh.forEach(item => {
              if (item.ypsl === '票量充足') {
                item.ypsl = '有'
              }
            })
          }
        })
        this.trainList = list.filter(item => {
          return this.trainQuery.isGD ? (item.cclx === 'G' || item.cclx === 'D') : item.cclx !== ''
        })
        if (this.isSortTime) {
          this.sortByTime()
        } else if (this.isSortDuration) {
          this.sortByDuration()
        }
        if (this.trainList.length > 0) {
          this.queryTip = '共查到' + this.trainList.length + '趟火车'
        } else {
          this.queryTip = '没有查到运行的火车车次'
        }
        this.showQueryTip = true
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          this.showQueryTip = false
        }, 3000)
      })
    },
    pre () {
      if (this.departureDate === this.moment().format('YYYY-MM-DD')) {
        return
      }
      this.departureDate = this.moment(this.departureDate).subtract(1, 'days').format('YYYY-MM-DD')
    },
    next () {
      this.departureDate = this.moment(this.departureDate).add(1, 'days').format('YYYY-MM-DD')
    },
    scrollStart (x) {
      this.positionY = this.$refs.scroll.scroll.y
    },
    scroll (pos, dir) {
      if (dir > 0 && Math.abs(pos.y - this.positionY) > 150) {
        this.$refs.bottomOpt.style.height = 0
      } else if (dir < 0 && Math.abs(pos.y - this.positionY) > 150) {
        this.$refs.bottomOpt.style.height = '40px'
      }
    },
    order () {
      this.$vux.toast.text('暂不支持预订火车票功能', 'middle')
    },
    sortByDuration () {
      this.trainList.sort((o1, o2) => {
        return o1.yxsj - o2.yxsj
      })
      this.isSortDuration = true
      this.isSortTime = false
    },
    sortByTime () {
      this.trainList.sort((o1, o2) => {
        return o1.cfsj - o2.cfsj
      })
      this.isSortDuration = false
      this.isSortTime = true
    }
  },
  watch: {
    departureDate () {
      this._queryTrain()
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'

.trainList-wrapper
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  background-color $color-background
  z-index 101
.fade-enter-active, .fade-leave-active
  animation-duration .5s
.calendar-opt
  display flex
  justify-content space-between
  align-items center
  color #fff
  background $color-theme
  padding 12px 15px
  .disabled
    color #ddd
.bottom-opt
  height 40px
  line-height 40px
  padding 0 15px
  background #444
  position absolute
  bottom 0
  left 0
  right 0
  z-index 999
  display flex
  justify-content space-between
  transition height .4s
  li
    width 33%
    text-align center
    color #fff
    font-size 16px
    font-weight normal
    position relative
    margin-right -1px
    &:after
      content ''
      display block
      position absolute
      right 0
      top 10px
      width 1px
      height 20px
      background #fff
    &:last-child
      &:after
        display none
.active-text
  color $color-theme !important
.query-tip
  color #fff
  font-size 16px
  height 35px
  line-height 35px
  text-align center
  background rgba(0, 206, 185, 0.6)
  position absolute
  top 0
  left 0
  right 0
  z-index 102
.train-list
  .train-item
    padding 12px 15px
    margin-bottom 8px
    background #ffffff
  .main
    display flex
    align-items center
    .left
      width 75%
      display flex
      justify-content space-between
      .left-item
        text-align center
      .center
        font-size 13px
        width 80px
        padding-top 2px
      .time
        font-size 18px
        color #000000
        line-height 1.2
        margin-bottom 3px
      .name
        font-size 16px
      .line
        height 1px
        width 55px
        background #999
        margin 3px auto
        position relative
        display block
        &:before
          content ''
          display block
          width 6px
          height 6px
          border 1px solid #999
          border-radius 50%
          background #fff
          position absolute
          left -2px
          top -4px
        &:after
          content ''
          display block
          width 6px
          height 6px
          border 1px solid #999
          border-radius 50%
          background #fff
          position absolute
          right -2px
          top -4px
      .active1
        &:before
          background #999 !important
      .active2
        &:after
          background #999 !important
    .right
      width 25%
      text-align right
      .price
        color red
        line-height 1
        margin-bottom 4px
      .btn
        display inline-block
        font-size 15px
        line-height 1
        background $color-theme
        color #fff
        padding 4px 9px
        border-radius 3px
      .toast
        color #999
  .bottom
    line-height 1
    margin-top 8px
    li
      display inline-block
      text-align left
      font-size 12px
      width 25%
      text-align center
      &:first-child
        text-align left
      &:nth-child(4)
        text-align right
    .no-ticket
      color #999
.calender-wrapper
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  z-index 102
.calendar-dropdown
  position fixed
  left 50%
  top 120px
  z-index 103
  transform translateX(-50%)
  padding 20px
  border 1px solid #eee
  border-radius 5px
  filter drop-shadow(2px 2px 12px #bfbfbf)
  background #fff
  &:before
    content ''
    display block
    position absolute
    top -16px
    left calc(50% - 15px)
    width 0
    height 0
    border-left 15px solid transparent
    border-right 15px solid transparent
    border-bottom 16px solid #eee
  &:after
    content ''
    display block
    position absolute
    top -15px
    left 50%
    left calc(50% - 15px)
    width 0
    height 0
    border-left 15px solid transparent
    border-right 15px solid transparent
    border-bottom 16px solid #fff
</style>
